summaryrefslogtreecommitdiff
path: root/app/api/tech-sales-rfqs/[rfqId]/vendors/[vendorId]/comments/route.ts
blob: 4578d4c5cf07cc3190069f2ed3681cebb39ab24f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { NextRequest, NextResponse } from "next/server"

import db from '@/db/db';
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"

import { techSalesRfqComments, techSalesRfqCommentAttachments, users } from "@/db/schema"
import { revalidateTag } from "next/cache"
import { eq, and } from "drizzle-orm"

// 파일 저장을 위한 유틸리티는 이제 saveFile 함수를 사용

/**
 * 코멘트 조회 API 엔드포인트
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ rfqId: string; vendorId: string }> }
) {
  try {
    // 인증 확인
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: "인증이 필요합니다" },
        { status: 401 }
      )
    }

    // params await (nextjs 15's requirement)
    const { rfqId: rfqIdStr, vendorId: vendorIdStr } = await params;
    const rfqId = parseInt(rfqIdStr)
    const vendorId = parseInt(vendorIdStr)

    // 유효성 검사
    if (isNaN(rfqId) || isNaN(vendorId)) {
      return NextResponse.json(
        { success: false, message: "유효하지 않은 매개변수입니다" },
        { status: 400 }
      )
    }

    // 코멘트 조회 (첨부파일 별도 조회)
    const comments = await db
      .select({
        id: techSalesRfqComments.id,
        rfqId: techSalesRfqComments.rfqId,
        vendorId: techSalesRfqComments.vendorId,
        userId: techSalesRfqComments.userId,
        content: techSalesRfqComments.content,
        isVendorComment: techSalesRfqComments.isVendorComment,
        createdAt: techSalesRfqComments.createdAt,
        updatedAt: techSalesRfqComments.updatedAt,
        isRead: techSalesRfqComments.isRead,
        userName: users.name,
      })
      .from(techSalesRfqComments)
      .leftJoin(users, eq(techSalesRfqComments.userId, users.id))
      .where(
        and(
          eq(techSalesRfqComments.rfqId, rfqId),
          eq(techSalesRfqComments.vendorId, vendorId)
        )
      )
      .orderBy(techSalesRfqComments.createdAt);

    // 각 코멘트의 첨부파일 조회
    const formattedComments = await Promise.all(
      comments.map(async (comment) => {
        const attachments = await db
          .select({
            id: techSalesRfqCommentAttachments.id,
            fileName: techSalesRfqCommentAttachments.fileName,
            originalFileName: techSalesRfqCommentAttachments.originalFileName,
            fileSize: techSalesRfqCommentAttachments.fileSize,
            fileType: techSalesRfqCommentAttachments.fileType,
            filePath: techSalesRfqCommentAttachments.filePath,
            uploadedAt: techSalesRfqCommentAttachments.uploadedAt,
          })
          .from(techSalesRfqCommentAttachments)
          .where(eq(techSalesRfqCommentAttachments.commentId, comment.id));

        return {
          ...comment,
          attachments,
        };
      })
    );

    return NextResponse.json({
      success: true,
      data: formattedComments
    })
  } catch (error) {
    console.error("techSales 코멘트 조회 오류:", error)
    return NextResponse.json(
      { success: false, message: "코멘트 조회 중 오류가 발생했습니다" },
      { status: 500 }
    )
  }
}

/**
 * 코멘트 생성 API 엔드포인트
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ rfqId: string; vendorId: string }> }
) {
  try {
    // 인증 확인
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: "인증이 필요합니다" },
        { status: 401 }
      )
    }

    // params await
    const { rfqId: rfqIdStr, vendorId: vendorIdStr } = await params;
    const rfqId = parseInt(rfqIdStr)
    const vendorId = parseInt(vendorIdStr)

    // 유효성 검사
    if (isNaN(rfqId) || isNaN(vendorId)) {
      return NextResponse.json(
        { success: false, message: "유효하지 않은 매개변수입니다" },
        { status: 400 }
      )
    }

    // FormData 파싱
    const formData = await request.formData()
    const content = formData.get("content") as string
    const isVendorComment = formData.get("isVendorComment") === "true"
    const files = formData.getAll("attachments") as File[]

    console.log("POST 요청 파라미터:", { rfqId, vendorId, content, isVendorComment, filesCount: files.length });

    if (!content && files.length === 0) {
      return NextResponse.json(
        { success: false, message: "내용이나 첨부파일이 필요합니다" },
        { status: 400 }
      )
    }

    // 세션 사용자 ID 확인
    if (!session.user.id) {
      return NextResponse.json(
        { success: false, message: "사용자 ID를 찾을 수 없습니다" },
        { status: 400 }
      )
    }

    // 코멘트 생성
    console.log("코멘트 생성 시도:", {
      rfqId,
      vendorId,
      userId: parseInt(session.user.id),
      content,
      isVendorComment,
    });

    const [comment] = await db
      .insert(techSalesRfqComments)
      .values({
        rfqId,
        vendorId,
        userId: parseInt(session.user.id),
        content,
        isVendorComment,
        isRead: !isVendorComment, // 본인 메시지는 읽음 처리
        createdAt: new Date(),
        updatedAt: new Date(),
      })
      .returning()

    console.log("코멘트 생성 성공:", comment);

    // 첨부파일 처리
    const attachments = []
    if (files.length > 0) {
      console.log("첨부파일 처리 시작:", files.length);
      
      // saveFile 함수 import
      const { saveFile } = await import('@/lib/file-stroage')

      // 각 파일 저장
      for (const file of files) {
        const saveResult = await saveFile({
          file,
          directory: `techsales-rfq/${rfqId}/vendor-${vendorId}/comment-${comment.id}`,
          originalName: file.name
        })

        if (!saveResult.success) {
          throw new Error(saveResult.error || '파일 저장에 실패했습니다.')
        }
        
        // DB에 첨부파일 정보 저장
        const [attachment] = await db
          .insert(techSalesRfqCommentAttachments)
          .values({
            rfqId,
            commentId: comment.id,
            fileName: saveResult.fileName!, // 해시된 파일명 (저장용)
            originalFileName: saveResult.originalName!, // 원본 파일명 (표시용)
            fileSize: file.size,
            fileType: file.type,
            filePath: saveResult.publicPath!,
            isVendorUpload: isVendorComment,
            uploadedBy: parseInt(session.user.id),
            vendorId,
            uploadedAt: new Date(),
          })
          .returning()
        
        attachments.push({
          id: attachment.id,
          fileName: attachment.fileName,
          originalFileName: attachment.originalFileName,
          fileSize: attachment.fileSize,
          fileType: attachment.fileType,
          filePath: attachment.filePath,
          uploadedAt: attachment.uploadedAt
        })
      }
      
      console.log("첨부파일 처리 완료:", attachments.length);
    }

    // 캐시 무효화
    revalidateTag(`tech-sales-rfq-${rfqId}-comments`)

    // 응답 데이터 구성
    const responseData = {
      id: comment.id,
      rfqId: comment.rfqId,
      vendorId: comment.vendorId,
      userId: comment.userId,
      content: comment.content,
      isVendorComment: comment.isVendorComment,
      createdAt: comment.createdAt,
      updatedAt: comment.updatedAt,
      userName: session.user.name,
      attachments,
      isRead: comment.isRead
    }

    console.log("응답 데이터:", responseData);

    return NextResponse.json({
      success: true,
      data: { comment: responseData }
    })
  } catch (error) {
    console.error("techSales 코멘트 생성 오류:", error)
    console.error("Error stack:", error instanceof Error ? error.stack : "Unknown error");
    return NextResponse.json(
      { success: false, message: "코멘트 생성 중 오류가 발생했습니다", error: error instanceof Error ? error.message : "Unknown error" },
      { status: 500 }
    )
  }
}